<template>
  <page-container>
    <div style="margin: 10px 0">
      {{ status }}
      <template v-if="status === 'CONNECTING'">loading</template>
      <el-alert v-else-if="status === 'OPEN'" type="success">链接成功</el-alert>
      <el-alert v-else type="error">断开链接</el-alert>
    </div>

    <el-button @click="sendMsg">发射</el-button>
    <el-button @click="close(1000)">断开</el-button>
    <el-button @click="open">重连</el-button>
  </page-container>
</template>

<script lang="ts" setup name="ExWebSocketPage">
  import { useWebSocket } from '@vueuse/core';
  import { ElNotification } from 'element-plus';

  const { open, close, send, status } = useWebSocket(
    'ws://124.222.224.186:8800',
    {
      autoReconnect: {
        delay: 1000,
        retries: 10000
      },
      onConnected: () => {
        ElNotification.success({
          message: '链接成功'
        });
      },
      onMessage(ws, event) {
        ElNotification.info({
          dangerouslyUseHTMLString: true,
          message: event.data
        });
      },
      onError(ws) {
        console.log(ws);
        ElNotification.error({
          message: '链接错误'
        });
      },
      onDisconnected() {
        ElNotification.error({
          message: '断开链接'
        });
      }
    }
  );

  const sendMsg = () => {
    send('hello world');
  };
</script>

<style lang="less" scoped>
  .title {
    font-size: 16px;
    font-weight: bold;
    margin: 10px;
  }
</style>
